package cn.edu.buaa.cnsatm.traffic_big_data_server.util;

import org.apache.kafka.connect.data.Decimal;

import java.awt.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 * @name = LX
 * @classname = CorrdinateUtil
 * @description =
 * @date = 2019/12/4
 */
public class CorrdinateUtil {
    public static BigDecimal sqrt(BigDecimal value, int scale){
        BigDecimal num2 = BigDecimal.valueOf(2);
        int precision = 100;
        MathContext mc = new MathContext(precision, RoundingMode.HALF_UP);
        BigDecimal deviation = value;
        int cnt = 0;
        while (cnt < precision) {
            deviation = (deviation.add(value.divide(deviation, mc))).divide(num2, mc);
            cnt++;
        }
        deviation = deviation.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return deviation;
    }

    public static Point2D bd_encrypt(double gg_lat, double gg_lon)

    {

        double x = gg_lon, y = gg_lat;

        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);

        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);

        return new Point2D(z * Math.cos(theta) + 0.0065,  z * Math.sin(theta) + 0.006);

    }

    public static Point2D bd_decrypt(double bd_lat, double bd_lon)

    {

        double x = bd_lon - 0.0065, y = bd_lat - 0.006;

        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);

        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);

        return new Point2D(z * Math.cos(theta), z * Math.sin(theta));
    }

    public static Point2D bd_decrypt(Point2D bd)
    {
        //高精度重写
        BigDecimal x = bd.getBX().subtract(new BigDecimal("0.0065"));
        BigDecimal y = bd.getBY().subtract(new BigDecimal("0.006"));
        BigDecimal z = x.multiply(x).add(y.multiply(y));
        z = sqrt(z, 1000);
        BigDecimal p = new BigDecimal(Math.sin(y.multiply(new BigDecimal(Math.PI)).doubleValue()));
        p = p.multiply(new BigDecimal("0.00002"));
        z = z.subtract(p);
        BigDecimal atan2 = new BigDecimal(Math.atan2(y.doubleValue(), x.doubleValue()));
        BigDecimal q = new BigDecimal(Math.cos(x.multiply(new BigDecimal(Math.PI)).doubleValue()));
        q = q.multiply(new BigDecimal("0.000003"));
        BigDecimal theta = atan2.subtract(q);
        return new Point2D(
                z.multiply(new BigDecimal(Math.cos(theta.doubleValue()))),
                z.multiply(new BigDecimal(Math.sin(theta.doubleValue())))
        );
    }
}
